package com.soft.servlets;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.soft.pojo.Result;
import com.soft.pojo.User;
import com.soft.service.UserService;
import com.soft.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService service = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("pwd");
        User user = service.searchUserByUserNameAndPwd(username,password);
        Result result = null;
        if(user == null){
            result = Result.error("用户名或密码错误");
        }else {
            result = Result.success(user);
        }
        //将result对象转换成json，响应给客户端
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(result);
        resp.setContentType("application/json");
        resp.getWriter().print(json);

    }
}
